import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { FetchService } from '../../../../../core/net/fetch.service';
import { GateJiezhiDetailComponent } from '../../gate-jiezhi-detail/gate-jiezhi-detail.component';
import * as _ from 'lodash';
import { forkJoin } from 'rxjs';
import { NzModalService } from 'ng-zorro-antd';
import { HttpClient } from '@angular/common/http';

const stationHash = {
    '168': '跃进渠一所',
    '169': '跃进渠二所'
};

@Component({
    selector: 'app-gt-control-check',
    templateUrl: './gt-control-check.component.html',
    styleUrls: ['../gate-control-list.component.scss', './gt-control-check.component.scss']
})
export class GtControlCheckComponent implements OnInit {
    tableData = [];
    pageNum = 1;
    pageSize = 10;
    total: number;
    loading = false;
    searchForm: FormGroup;
    sectionList = [];
    controlList = [];
    rtuUrl = (window as any).environment.rtuUrl;
    constructor(private router: Router,
                private fb: FormBuilder,
                private http: HttpClient,
                private modalService: NzModalService,
                private fetchService: FetchService) {
        this.searchForm = this.fb.group({
            watergateCode: [],
            sectionId: ['168'],
            section2Id: []
        });
    }

    ngOnInit(): void {
        //  查询管理段
        this.fetchService.post<any>('sys/sysDictValue/list', { dictTypeId: '1022' })
            .subscribe(res => {

            });
        this.getSectionList();
        this.queryInfo();
    }
    getSectionList(): void {
        this.searchForm.patchValue({
            section2Id: null
        });
        this.fetchService.post('wrs/wrsBmanage/list', {
            pid: this.searchForm.get('sectionId').value
        }).subscribe(res => {
            this.sectionList = res['list'] || [];
        });
    }
    queryInfo(reset: boolean = false): void {
        if (reset) {
            this.pageNum = 1;
        }
        this.loading = true;
        const params = {
            ...this.searchForm.value,
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            watergateType: 4
        };
        this.fetchService.post('wrs/wrsBawaterGate/list', params).subscribe(res => {
            const list = res['list'] || [];
            // const data = list.filter(item => {
            //     return !!item.info;
            // });
            this.tableData = list.map(row => {
                return {
                    ...row,
                    stationName: stationHash[row.sectionId]
                };
            });
            this.total = res['total'];
            this.loading = false;
            this.fetchService.post<Array<any>>('wrs/wrsBawaterGate/gateInfo', {
                // sectionId: this.radioValue === '0' ? null : this.radioValue
            }).subscribe(resp => {

                    this.controlList = resp.map(item => {
                        return {
                            ...item,
                            title: item['watergateCode'],
                            warningLevel: item['gateInfo'].filter(info => {
                                return _.endsWith(info.itemId, 'WaterLevel');
                            })[0]['val'],
                            openInfo: item['gateInfo'].filter(info => {
                                return info.itemId.indexOf('Position') != -1;
                            })
                        };
                    });

            });
        });
    }

    directToSketchMap(): void {
        this.router.navigate(['/gate/gt-control']);
    }

    //  节制闸弹窗
    openJieZhiDetailModal(id): void {
        const data = this.controlList.find(item => {
            return item.id == id;
        });
        const groupIndexArr = data['groupIndex'].split(',');
        if (groupIndexArr.length < 2) {
            this.http.post(`${ this.rtuUrl }data/view`, {
                groupIndex: data['groupIndex'],
                serverIndex: '0'
            }).subscribe(res => {
                const list = res['data'];
                const keysArr = list.map(item => {
                    return item['col'];
                });
                const valsArr = list.map(item => {
                    return item['val'];
                });
                const modal = this.modalService.create({
                    nzTitle: data['watergateCode'],
                    nzClassName: 'custom-modal',
                    nzWidth: 1598,
                    nzBodyStyle: {
                        background: '#eee',
                        margin: 0,
                        padding: '5px'
                    },
                    nzContent: GateJiezhiDetailComponent,
                    nzFooter: null,
                    nzComponentParams: {
                        dianbiaoData: _.zipObject(keysArr, valsArr),
                        dianbiaoData2: null,
                        jzData: data,
                        groupIndex: data['groupIndex']
                    }
                });
                modal.afterOpen.subscribe(() => console.log('[afterOpen] emitted!'));

                // Return a result when closed
                modal.afterClose.subscribe(result => console.log('[afterClose] The result is:', result));

            });
        } else {
            //  余丁 有6孔 需要分两组获取数据
            const yuding1 = this.http.post(`${ this.rtuUrl }data/view`, {
                groupIndex: '6',
                serverIndex: '0'
            });
            const yuding2 = this.http.post(`${ this.rtuUrl }data/view`, {
                groupIndex: '7',
                serverIndex: '0'
            });
            forkJoin(yuding1, yuding2).subscribe(res => {
                if (res) {
                    const list1 = res[0]['data'];
                    const list2 = res[1]['data'];
                    const keysArr1 = list1.map(item => {
                        return item['col'];
                    });
                    const valsArr1 = list1.map(item => {
                        return item['val'];
                    });
                    const keysArr2 = list2.map(item => {
                        return item['col'];
                    });
                    const valsArr2 = list2.map(item => {
                        return item['val'];
                    });
                    const modal = this.modalService.create({
                        nzTitle: data['watergateCode'],
                        nzClassName: 'custom-modal',
                        nzWidth: 1598,
                        nzBodyStyle: {
                            background: '#eee',
                            margin: 0,
                            padding: '5px'
                        },
                        nzContent: GateJiezhiDetailComponent,
                        nzFooter: null,
                        nzComponentParams: {
                            dianbiaoData: _.zipObject(keysArr1, valsArr1),
                            dianbiaoData2: _.zipObject(keysArr2, valsArr2),
                            jzData: data,
                            groupIndex: data['groupIndex']
                        }
                    });
                }
            });
        }

    }
}
